const app = getApp()
const MMPDB = wx.cloud.database();
const graph = MMPDB.collection('articles');
const category = MMPDB.collection('category');
const _ = MMPDB.command;
Page({
  data: {
    //wode
    current: 'homePage',
    current_scroll: 'tab0',
    spinShow: true,
    hotArticles: [],
    homeCategory: [],
    listArticles: [],

    findCategory: [],
    findeDetail: {},

    homePage: 0,
    homeSize: 10,

    page: 0,
    size: 10,
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  handleChange({
    detail
  }) {

    var url;
    switch (detail.key) {
      case "homePage":

        url = '/pages/index/index';

        break;
      case "mine":
        url = '/pages/me/index';
        break;
    }
    this.setData({
      current: detail.key
    });
    wx.redirectTo({
      url: url,
    })

  },

  handleChangeScroll({
    detail
  }) {
    var that = this;
    that.setData({
      spinShow: true,
      page: 0
    });
    var obj = [];
    //


    (that.data.homeCategory || []).forEach(function (item) {
      if (item.category == detail.key) {
        detail.id = item.id;
        detail.belong = item.belong;
      }
    });

    obj.push(_.eq(detail.key));

    if (detail.belong == 0) {
      wx.cloud.callFunction({
        name: 'categoryChange',
        data: {
          id: detail.id,
        },
        complete: res => {

          if (res.result.data.length > 0) {
            (res.result.data || []).forEach(function (item) {
              obj.push(_.eq(item.category));
            });

          }
          that.categoryChange(obj, detail);

        },
      })
    } else {
      that.categoryChange(obj, detail);
    }
    that.setData({
      current_scroll: detail.key
    });



  },
  categoryChange: function (obj, detail) {

    var that = this;
    graph.where({
      article_category: _.or(obj)
    }).orderBy('article_publish_time', 'desc').skip(that.data.page).limit(that.data.size).get().then(res => {
      var listArticles = that.data.listArticles;
      if (that.data.page == 0) {
        listArticles = res.data;
      } else {

        (res.data || []).forEach(function (item) {
          listArticles.unshift(item);
        });
      }
      that.setData({
        listArticles: listArticles
      });
      that.setData({
        spinShow: false,
        findCategory: obj,
        findDetail: detail
      });
      wx.stopPullDownRefresh();
    }).catch(console.error)
  },
  homeArticle: function () {
    var that = this;
    graph.orderBy('article_publish_time', 'desc').orderBy('article_volume', 'desc').skip(that.data.homePage).limit(that.data.homeSize).get().then(res => {

      var hotArticles = that.data.hotArticles;
      if (that.data.homePage == 0) {
        hotArticles = res.data;
      } else {
        (res.data || []).forEach(function (item) {
          hotArticles.unshift(item);
        });
      }

      that.setData({
        hotArticles: hotArticles,
        spinShow: false
      });
    })
  },

  //end 事件处理函数
  onLoad: function () {
    // wx.getSetting({
    //   success(res) {
    //     if (!res.authSetting['scope.userInfo']) {
    //       wx.authorize({
    //         scope: 'scope.userInfo',
    //         success() {
    //           // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
    //           wx.getUserInfo({
    //             success: res => {
    //               app.globalData.userInfo = res.userInfo
    //               that.setData({
    //                 userInfo: res.userInfo,
    //                 hasUserInfo: true
    //               })
    //             }
    //           })
    //         }
    //       })
    //     }
    //   }
    // })
    var that = this;


    var c = that.initChart;
    that.setData({
      ec: {
        onInit: c
      }
    })
    that.homeArticle();
    category.where({
      recommend: 1
    }).orderBy('sort', 'desc').get().then(res => {

      that.setData({
        homeCategory: res.data
      });
    })






  },
  onPullDownRefresh: function () {
    var that = this;
    var page;
    if (that.data.current_scroll == "tab0") {
      page = that.data.homePage + that.data.homeSize;

      that.setData({
        spinShow: true,
        homePage: page
      });
      that.homeArticle();
    } else {
      page = that.data.page + that.data.size;
      that.setData({
        spinShow: true,
        page: page
      });

      that.categoryChange(that.data.findCategory, that.data.findeDetail);
    }

  }, onShareAppMessage() {
    return {
      title: '养生老中医',
      imageUrl: 'https://6c61-laozhongyi-f1f28d-1258321215.tcb.qcloud.la/logo.png?sign=9a5ff58e454f0217a83f8840eb1e28b5&t=1545637466',
      path: '/pages/index/index'
    }
  }
})